# import os, fitz
# import PySimpleGUI as psg
#
#
# def img2pdf(tar_pdf_path, imgdir):
#     doc = fitz.open()  # PDF with the pictures
#     imglist = os.listdir(imgdir)  # list of them
#     imglist.sort(key=lambda book: int(book.replace('.jpg', '').replace('.png', '')))    # 排序
#     imgcount = len(imglist)  # pic count
#
#     for i, f in enumerate(imglist):
#         img = fitz.open(os.path.join(imgdir, f))  # open pic as document
#         # print(f'img[0]: {img[0]}')
#         # print(f'img[1]: {img[1]}')
#         rect = img[0].rect  # pic dimension
#         pdfbytes = img.convert_to_pdf()  # make a PDF stream
#         img.close()  # no longer needead
#         imgPDF = fitz.open("tar_pdf", pdfbytes)  # open stream as PDF
#         page = doc.new_page(width=rect.width,  # new page with ...
#                             height=rect.height)  # pic dimension
#         page.show_pdf_page(rect, imgPDF, 0)  # image fills the page
#         psg.OneLineProgressMeter("Import Images",  # show our progress
#                                  i + 1, imgcount)
#
#     print('生成pdf: {}'.format(tar_pdf_path))
#     doc.save(tar_pdf_path)
#
# def clear_dir(imgdir):
#     imglist = os.listdir(imgdir)
#     for img in imglist:
#         os.remove(imgdir+img)
#
#
# if __name__ == '__main__':
#     img_dir = r"./img/"
#     tar_pdf_path = r"./pdf/output.pdf"
#
#     img2pdf(tar_pdf_path, img_dir)
#
#     clear_dir(img_dir)
#
#

import img2pdf as imp
import  os


def from_photo_to_pdf(photo_path):
    photo_list = os.listdir(photo_path)
    photo_list = [os.path.join(photo_path,i) for i in photo_list]
    return photo_list

def img2pdf(tar_pdf_path, imgdir):
    photo_list = from_photo_to_pdf(imgdir)
    # a4inpt = (imp.mm_to_pt(720), imp.mm_to_pt(1080))
    # layout_fun = imp.get_layout_fun(a4inpt)
    with open(tar_pdf_path, 'wb') as f:
        # f.write(imp.convert(photo_list, layout_fun=layout_fun))
        f.write(imp.convert(photo_list))

def clear_dir(imgdir):
    imglist = os.listdir(imgdir)
    for img in imglist:
        os.remove(imgdir+img)


if __name__ == '__main__':
    img_dir = r"./img/"
    tar_pdf_path = r"./pdf/output.pdf"

    img2pdf(tar_pdf_path, img_dir)

    clear_dir(img_dir)


